class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:mobile]
  validates :mobile, uniqueness: true
  validates :mobile, presence: true
  # validates :password, length: { in: 8..20 }, on: :update, allow_blank: true
  #validates :citizen_id, length: { is: 18 }


  mount_uploader :picture_citizen_card_front, PictureUploader
  mount_uploader :picture_citizen_card_back, PictureUploader
  mount_uploader :picture_business_license, PictureUploader

  has_many :credit_records
  has_many :traffic_violations

  paginates_per 10
  
  include Workflow
  workflow do
    state :new do
      event :certify, :transitions_to => :awaiting_certification
    end

    state :awaiting_certification do
      event :comfirm_individual, :transitions_to => :certified_individual
      event :comfirm_company, :transitions_to => :certified_company
      event :reject, :transitions_to => :new
    end

    state :certified_individual do
      event :certify, :transitions_to => :awaiting_certification
    end

    state :certified_company
  end

  def realname_ellipsis(length=1)
    if self && self.realname.length > length
      return self.realname[0,1] + '*****'
    end
    self.realname
  end

  # def company_ellipsis(length=1)
  #   if self && self.company_name.length > length
  #     return self.company_name[0,1] + '*****'
  #   end
  #   self.company_name
  # end
  
  def readable_state

    sstate = ''
    if self.current_state == 'new'
      sstate = '未认证'
    elsif self.current_state == 'awaiting_certification'
      sstate = '等待认证'
    elsif self.current_state == 'certified_individual'
      sstate = '个人已认证'
    elsif self.current_state == 'certified_company'
      sstate = '公司已认证'
    end
    sstate
  end

  def workflow_state_class
    
    sstate = ''

    if self.current_state == 'new'
      sstate = 'label-default'
    elsif self.current_state == 'awaiting_certification'
      sstate = 'label-warning'
    elsif self.current_state == 'certified_individual'
      sstate = 'label-success'
    elsif self.current_state == 'certified_company'
      sstate = 'label-success'
    end

    sstate
  end

  def credit_records_size
    self.credit_records.size()
  end
  protected

  def email_required?
    false
  end

end
